import { ResConfig, UIConfig } from "../../SysConfig/SysConfig";
import ResManage from "../ResManage";
import UIBasic from "./UIBasic";
import UIMaskBg from "./UIMaskBg";
import UIPlaneInfo from "./UIPlanInfo";




const { ccclass, property } = cc._decorator;

@ccclass
export default class UIManage extends cc.Component {

    public static Instance: UIManage = null;

    //固定父级节点
    private m_fixed: cc.Node = null;
    private m_popUp: cc.Node = null;
    private m_gameLanch: cc.Node = null;

    /**所有加载过的, 且没有释放的窗体 */
    private m_allFormMap: Map<UIConfig.UI_TYPE_ID, UIBasic> = new Map();
    /**窗体是否处于加载中状态 */
    private m_loadingMap: Map<UIConfig.UI_TYPE_ID, Boolean> = new Map();
    /**当前显示中的窗体 */
    private m_curShowMap: Map<UIConfig.UI_TYPE_ID, UIBasic> = new Map();

    /**用于存储1和3level的窗体，主要用于遮罩背景变更 */
    private m_planeStack: Array<UIBasic> = [];

    private m_animationManage: Array<UIBasic> = new Array();

    onLoad() {
        if (UIManage.Instance == null) {
            UIManage.Instance = this;
        }
        else {
            this.destroy();
            return;
        }

        this.m_fixed = cc.find('UIROOT/Fixed', this.node);
        this.m_popUp = cc.find('UIROOT/PopUp', this.node);
        this.m_gameLanch = this.node;
    }

    start() {
        UIMaskBg.GetInstance().init();
        UIPlaneInfo.GetInstance().init();
    }

    public getFixedNode() {
        return this.m_fixed;
    }

    public getPopUpNode() {
        return this.m_popUp;
    }

    public getGameLanchNode() {
        return this.m_gameLanch;
    }


    public ShowUIPannelByID(ui_uid: UIConfig.UI_TYPE_ID, onComplete: (asset: cc.Node) => void) {
        let uiPlaneInfo = this.getUIPlaneInfoById(ui_uid);
        if (uiPlaneInfo == null) {
            console.warn('配置信息中不存在!!!');
            return;
        }

        //窗体ID 是否存在与显示窗体存储中
        let uiBasic: UIBasic = this.m_curShowMap.get(ui_uid);
        if (uiBasic) {
            console.log(ui_uid + '窗体ID->存在显示窗体存储中');
            onComplete(uiBasic.node);
            return;
        }

        //窗体ID 是否加载进行中
        let isLoading = this.m_loadingMap.get(ui_uid);
        if (isLoading) {
            console.log(ui_uid + '窗体ID->加载中... ...');
            return;
        }
        this.m_loadingMap.set(ui_uid, true);


        //1级面板存在互斥比如：A面板处于显示中，当打开B面板后；此时A面板需要自动关闭(A和B均为1级面板)
        if (uiPlaneInfo._uiLevel == 1) {
            for (let i = this.m_planeStack.length - 1; i >= 0; i--) {
                let _uiBasic = this.m_planeStack[i];
                let _uiPlaneInfo = this.getUIPlaneInfoById(_uiBasic.ui_uid);
                if (_uiBasic.ui_state == 0 && _uiPlaneInfo._uiLevel == 1) {
                    _uiBasic.ui_state = 1;
                    this.InstantReleaseUIPannel(_uiBasic.ui_uid);
                }
            }
        }

        //进入加载；1、当内存中存在从内存加载，2、直接从资源包中加载（这两个都是异步，内存中会比较快）。
        let self = this;
        ResManage.Instance.loadAssetByBoundle(ResConfig.PrefabBundle, uiPlaneInfo._uiPath + uiPlaneInfo._uiName, cc.Prefab, (err: Error, asset: cc.Prefab) => {
            if (err) {
                //删除加载状态
                self.m_loadingMap.delete(ui_uid);
            }
            else {
                //实例化预制体
                let newNode = cc.instantiate(asset);
                newNode.parent = self.m_gameLanch;
                newNode.x = newNode.y = 0;
                newNode.active = true;

                uiBasic = newNode.getComponent(UIBasic);
                if (uiBasic) {
                    uiBasic.ui_uid = ui_uid;
                    uiBasic.ui_time = 0;
                    uiBasic.ui_state = 0;
                    uiBasic.node.scale = 1;

                    //加载成功的窗体加入存储
                    self.m_curShowMap.set(ui_uid, uiBasic);
                    self.m_allFormMap.set(ui_uid, uiBasic);
                    UIMaskBg.GetInstance().showMaskBg(ui_uid);

                    //满足面板等级 
                    if (uiPlaneInfo._uiLevel == 1 || uiPlaneInfo._uiLevel == 3) {
                        this.m_planeStack.push(uiBasic);
                    }
                }
                else {
                    console.warn(ui_uid + '窗体ID->无法获取到!!!')
                    newNode.destroy();
                    ResManage.Instance.releaseAssetByBoundle(ResConfig.PrefabBundle, uiPlaneInfo._uiPath + uiPlaneInfo._uiName, cc.Prefab);
                }

                self.m_loadingMap.delete(ui_uid);
                onComplete(newNode);
            }
        });

    }

    /**立即释放 */
    public InstantReleaseUIPannel(ui_uid: UIConfig.UI_TYPE_ID) {
        let uiBasic = this.m_allFormMap.get(ui_uid);
        if (uiBasic) {
            let uiPlaneInfo = this.getUIPlaneInfoById(ui_uid);
            if (uiPlaneInfo) {
                //删除存储数据
                if (uiPlaneInfo._uiLevel == 1 || uiPlaneInfo._uiLevel == 3) {
                    let index = this.m_planeStack.indexOf(uiBasic);
                    if (index != -1) {
                        this.m_planeStack.splice(index, 1)
                    }
                }

                this.m_curShowMap.delete(ui_uid);
                this.m_allFormMap.delete(ui_uid);
                uiBasic.node.destroy();
                //从内存释放
                if (uiPlaneInfo._uiRelease) {
                    ResManage.Instance.releaseAssetByBoundle(ResConfig.PrefabBundle, uiPlaneInfo._uiPath + uiPlaneInfo._uiName, cc.Prefab);
                }

                //遮罩背景改变
                UIMaskBg.GetInstance().hideMaskBg(ui_uid);
            }
        }
    }


    /**延迟释放，存在一个动画效果 */
    public DelayReleaseUIPannel(ui_uid: UIConfig.UI_TYPE_ID) {
        let uiBasic = this.m_curShowMap.get(ui_uid);
        if (uiBasic) {
            if (uiBasic.ui_state == 0) {
                uiBasic.ui_state = 1;
                this.m_animationManage.push(uiBasic);
            }
        }
    }


    protected update(dt: number): void {
        for (let i = this.m_animationManage.length - 1; i >= 0; i--) {
            let uiBasic = this.m_animationManage[i];
            if (uiBasic) {
                uiBasic.ui_time += dt;
                if (uiBasic.ui_time < 1/*0.2*/) {
                    uiBasic.node.scale = 1 - uiBasic.ui_time / 1.2//uiBasic.ui_close_time / 0.2;
                } else {
                    uiBasic.node.scale = 0;
                    this.m_animationManage.splice(i, 1);
                    this.InstantReleaseUIPannel(uiBasic.ui_uid);
                }
            }
        }
    }


    /**
     * 获取下一个满足条件的面板节点
     * @returns 
     */
    public getNextUIPlaneById() {
        let index: number = 1;
        let uiBasic: UIBasic = null;

        for (let i = this.m_planeStack.length - 1; i >= 0; i--) {
            let _uiBasic = this.m_planeStack[i];
            let _uiPlaneInfo = this.getUIPlaneInfoById(this.m_planeStack[i].ui_uid);
            if (_uiBasic.ui_state == 0 && _uiPlaneInfo._uiMaskBg != 3) {
                uiBasic = this.m_planeStack[this.m_planeStack.length - index];
            }
            else {
                index++;
            }
        }

        return uiBasic?.node;
    }

    /**
     * 获取当前展示节点作为遮罩父节点
     * @param ui_uid 
     * @returns 
     */
    public getUIPlaneById(ui_uid: UIConfig.UI_TYPE_ID) {
        return this.m_curShowMap.get(ui_uid)?.node;
    }

    /**
     * 获取UI面板配置信息
     * @param ui_uid 
     * @returns 
     */
    public getUIPlaneInfoById(ui_uid: UIConfig.UI_TYPE_ID) {
        return UIPlaneInfo.GetInstance().getPlanInfo(ui_uid);
    }



}
